package com.go.where.manager.action.go;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.json.simple.JSONObject;

import com.go.where.manager.action.SuperAction;
import com.go.where.manager.common.Constants;
import com.go.where.manager.exception.ManagerException;
import com.go.where.manager.freemarker.CustomFreemarkerManager;
import com.go.where.manager.http.HttpClient;
import com.go.where.manager.page.Pagination;
import com.go.where.manager.pojo.TopicInfo;
import com.go.where.manager.service.TopicService;
import com.go.where.manager.util.CommonUtil;
import com.go.where.manager.util.KindEditUtil;

@InterceptorRefs( {
		@InterceptorRef(value = "defaultStack", params = { "maximumSize",
				"2048000", "allowedTypes",
				"image/bmp,image/png,image/gif,image/jpeg" }),
		@InterceptorRef(value = "defalutStackSet") })
public class TopicAction extends SuperAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4383195694100314090L;
	private static final Logger log = Logger.getLogger(TopicAction.class);

	public Pagination<?> page;

	@Resource(name = "topicService")
	private TopicService topicService;

	private TopicInfo topicInfo;
	private TopicInfo topicInfoQuery;

	private String topicId;

	private File prePhoto;// 上传的文件
	private String prePhotoFileName; // 文件名称
	private String prePhotoContentType; // 文件类型

	private File mainPhoto;// 上传的文件
	private String mainPhotoFileName; // 文件名称
	private String mainPhotoContentType; // 文件类型

	/**
	 * 查询列表
	 * 
	 * @return
	 */
	public String list() {
		if (topicInfoQuery == null) {
			topicInfoQuery = new TopicInfo();
			topicInfoQuery.setPageSize(Constants.INIT_PAGESIZE);
			topicInfoQuery.setCurrentPage(Constants.INIT_CURRENTPAGE);
		}
		try {
			topicInfoQuery.setIsDelete(Constants.NOT_DELETED);
			page = topicService.queryPage(topicInfoQuery);
		} catch (Exception e) {
			addActionError(e.getMessage());
			log.error("查询信息异常", e);
		}
		return LIST;
	}

	public String detail() {
		topicInfo = topicService.queryByPrimartKey(topicId);
		return "detail";
	}

	

	public String add() {
		return INPUT;
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public String save() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String savePath = ServletActionContext.getServletContext()
					.getRealPath(CommonUtil.FILE_SEPARATOR)
					+ Constants.MATERIAL_HTML;
			File htmlPath = new File(savePath);
			if (!htmlPath.exists()) {
				htmlPath.mkdirs();
			}
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_"
					+ new Random().nextInt(1000) + ".html";
			String urlPrefix = CustomFreemarkerManager.getValue("url.prefix");
			String htmlData = request.getParameter("content") != null ? request
					.getParameter("content") : "";
			log.info("获取富文本编辑器中内容：" + htmlData);
			htmlData = htmlData.replaceAll(Constants.PROJECT_NAME, urlPrefix
					+ Constants.PROJECT_NAME);
			log.info("替换后的内容：" + htmlData);
			StringBuilder sb = KindEditUtil.linkHtml(htmlData, topicInfo
					.getTopicName(), true);

			CommonUtil.createHtml(sb.toString(), savePath + newFileName);
			String previewRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.TOPIC_PREVIEW_IMAGES);
			String mainRealpath = ServletActionContext.getServletContext()
					.getRealPath(
							CommonUtil.FILE_SEPARATOR
									+ Constants.TOPIC_MAIN_IMAGES);
			String pre = KindEditUtil.uploadPicture(prePhoto, prePhotoFileName,
					previewRealpath, Constants.TOPIC_PREVIEW_IMAGES);
			String main = KindEditUtil.uploadPicture(mainPhoto,
					mainPhotoFileName, mainRealpath,
					Constants.TOPIC_MAIN_IMAGES);

			topicInfo.setTopicContentPath(urlPrefix + Constants.PROJECT_NAME
					+ CommonUtil.FILE_SEPARATOR + Constants.MATERIAL_HTML
					+ newFileName);
			topicInfo.setPrePhotoPath(pre);
			topicInfo.setMainPhotoPath(main);

			topicService.save(topicInfo, getCurrentOperator());
			redirectionUrl = "topic!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存信息异常", e);
			addActionError("保存信息异常！" + e);
			return this.add();
		}
	}
	
	public String toEdit() {
		try {
			topicInfo = topicService.queryByPrimartKey(topicId);
			topicInfo.setTopicContentPathUrl(topicInfo.getTopicContentPath());
			String htmlUrl = topicInfo.getTopicContentPath();
			String ip = CustomFreemarkerManager.getValue("ip.url.prefix");
			if (StringUtils.isNotBlank(ip)) {
				htmlUrl = htmlUrl.replace(CustomFreemarkerManager.getValue(
						"ip.url.prefix.common").trim(), ip.trim());
			}
			HttpClient hc = new HttpClient();
			String htmlContent = hc.doGet(htmlUrl, "utf-8");
			String[] htmls = null;
			if (StringUtils.isNotBlank(htmlContent)) {
				htmls = htmlContent.split("<body>");
				if (htmls.length > 1) {
					String bodyHtmlStr = htmls[1];
					if (StringUtils.isNotBlank(bodyHtmlStr)) {
						String[] bodyHtmls = bodyHtmlStr.split("</body>");
						String body = bodyHtmls[0];
						topicInfo.setTopicContentPath(this
								.htmlspecialchars(body));
					}
				}
			}
		} catch (Exception e) {
			addActionError("查询信息异常" + e.getMessage());
			log.error("查询信息异常", e);
		}
		return INPUT;
	}

	/**
	 * 编辑
	 * 
	 * @return
	 */
	public String edit() {
		try {
			HttpServletRequest request = ServletActionContext.getRequest();
			String savePath = ServletActionContext.getServletContext()
					.getRealPath(CommonUtil.FILE_SEPARATOR)
					+ Constants.MATERIAL_HTML;
			String[] htmlArr = topicInfo.getTopicContentPathUrl().split("/");
			String newFileName = htmlArr[htmlArr.length - 1];
			String materialUrlPrefix = CustomFreemarkerManager
					.getValue("url.prefix");
			String htmlData = request.getParameter("content") != null ? request
					.getParameter("content") : "";
			htmlData = htmlData.replaceAll(materialUrlPrefix
					+ Constants.PROJECT_NAME, Constants.PROJECT_NAME);
			htmlData = htmlData.replaceAll(Constants.PROJECT_NAME,
					materialUrlPrefix + Constants.PROJECT_NAME);
			StringBuilder sb = KindEditUtil.linkHtml(htmlData, topicInfo
					.getTopicName(), false);

			CommonUtil.createHtml(sb.toString(), savePath + newFileName);
			topicInfo.setTopicContentPath(materialUrlPrefix
					+ Constants.PROJECT_NAME + CommonUtil.FILE_SEPARATOR
					+ Constants.MATERIAL_HTML + newFileName);
			if (prePhoto != null) {
				String previewRealpath = ServletActionContext
						.getServletContext().getRealPath(
								CommonUtil.FILE_SEPARATOR
										+ Constants.TOPIC_PREVIEW_IMAGES);
				String pre = KindEditUtil.uploadPicture(prePhoto,
						prePhotoFileName, previewRealpath,
						Constants.TOPIC_PREVIEW_IMAGES);
				topicInfo.setPrePhotoPath(pre);
			}
			if (mainPhoto != null) {
				String mainRealpath = ServletActionContext.getServletContext()
						.getRealPath(
								CommonUtil.FILE_SEPARATOR
										+ Constants.TOPIC_MAIN_IMAGES);

				String main = KindEditUtil.uploadPicture(mainPhoto,
						mainPhotoFileName, mainRealpath,
						Constants.TOPIC_MAIN_IMAGES);
				topicInfo.setMainPhotoPath(main);
			}
			topicService.update(topicInfo, getCurrentOperator());
			redirectionUrl = "topic!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("修改信息异常", e);
			addActionError("修改信息异常！" + e);
			topicId = topicInfo.getTopicId();
			return this.toEdit();
		}
	}

	public String falseDelete() {
		topicInfo = new TopicInfo();
		topicInfo.setTopicId(topicId);
		topicInfo.setIsDelete(Constants.DELETED);
		try {
			topicService.update(topicInfo, getCurrentOperator());
			redirectionUrl = "topic!list.htm";
			return SUCCESS;
		} catch (Exception e) {
			log.error("删除信息异常", e);
			addActionError("删除信息异常" + e);
			return this.list();
		}
	}

	/**
	 * 富文本编辑器里上传图片
	 * 
	 * @return
	 * @throws FileUploadException
	 * @throws IOException
	 */

	public String imgUpload() throws FileUploadException, IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		String obj = "";
		try {
			obj = KindEditUtil.uploadImage(request, response, out,
					Constants.TOPIC_IMAGES);
		} catch (ManagerException e) {
			return e.getMessage();
		}
		// log.info(saveUrl);
		// 在编辑框内生成图片
		out.print(obj);
		return null;
	}

	/**
	 * 图片文件管理
	 * 
	 * @return
	 * @throws Exception
	 */

	public String fileManager() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter();
		JSONObject result = new JSONObject();
		try {
			result = KindEditUtil.fileManager(request, out,
					Constants.TOPIC_IMAGES);
		} catch (ManagerException e) {
			return null;
		}

		response.setContentType("application/json; charset=UTF-8");
		out.println(result.toJSONString());
		return null;
	}

	private String htmlspecialchars(String htmlStr) {
		htmlStr = htmlStr.replaceAll("&", "&amp;");
		htmlStr = htmlStr.replaceAll("<", "&lt;");
		htmlStr = htmlStr.replaceAll(">", "&gt;");
		htmlStr = htmlStr.replaceAll("\"", "&quot;");
		return htmlStr;
	}

	public Pagination<?> getPage() {
		return page;
	}

	public void setPage(Pagination<?> page) {
		this.page = page;
	}

	public TopicInfo getTopicInfo() {
		return topicInfo;
	}

	public void setTopicInfo(TopicInfo topicInfo) {
		this.topicInfo = topicInfo;
	}

	public TopicInfo getTopicInfoQuery() {
		return topicInfoQuery;
	}

	public void setTopicInfoQuery(TopicInfo topicInfoQuery) {
		this.topicInfoQuery = topicInfoQuery;
	}

	public String getTopicId() {
		return topicId;
	}

	public void setTopicId(String topicId) {
		this.topicId = topicId;
	}

	public File getPrePhoto() {
		return prePhoto;
	}

	public void setPrePhoto(File prePhoto) {
		this.prePhoto = prePhoto;
	}

	public String getPrePhotoFileName() {
		return prePhotoFileName;
	}

	public void setPrePhotoFileName(String prePhotoFileName) {
		this.prePhotoFileName = prePhotoFileName;
	}

	public String getPrePhotoContentType() {
		return prePhotoContentType;
	}

	public void setPrePhotoContentType(String prePhotoContentType) {
		this.prePhotoContentType = prePhotoContentType;
	}

	public File getMainPhoto() {
		return mainPhoto;
	}

	public void setMainPhoto(File mainPhoto) {
		this.mainPhoto = mainPhoto;
	}

	public String getMainPhotoFileName() {
		return mainPhotoFileName;
	}

	public void setMainPhotoFileName(String mainPhotoFileName) {
		this.mainPhotoFileName = mainPhotoFileName;
	}

	public String getMainPhotoContentType() {
		return mainPhotoContentType;
	}

	public void setMainPhotoContentType(String mainPhotoContentType) {
		this.mainPhotoContentType = mainPhotoContentType;
	}

}
